import axios from "axios";
import { CommonActions } from '@react-navigation/native';
import { navigationRef } from '../navigation/navigationRef';
import AsyncStorage from "@react-native-async-storage/async-storage";
import axiosRetry from 'axios-retry';

// 基础配置
const instance = axios.create({
  baseURL: "http://192.168.46.222:3000",
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  }
});

// 请求拦截器
instance.interceptors.request.use(
  async function (config) {
    console.log('开始请求:', config.url);
    // 获取访问令牌
    const accessToken = await AsyncStorage.getItem('accessToken');
    if (accessToken) {
      config.headers['Authorization'] = accessToken;
    }
    return config;
  },
  function (error) {
    console.log('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  async function (response) {
    console.log('响应数据:', response.data);

    // 如果是登录接口
    if (response.config.url === '/login') {
      const { setAccessToken, setRefreshToken, user } = response.data;
      if (setAccessToken && setRefreshToken) {
        // 保存令牌
        await AsyncStorage.setItem('accessToken', setAccessToken);
        await AsyncStorage.setItem('refreshToken', setRefreshToken);
        // 保存用户信息
        await AsyncStorage.setItem('userInfo', JSON.stringify(user));
      }
    }

    return response.data;
  },
  async function (error) {
    console.log('响应错误:', error);
    const originalRequest = error.config;
    if (error.response) {
      const status = error.response.status;

      switch (status) {
        case 400:
          return Promise.reject(new Error(error.response.data.message || '请求参数错误'));
        case 401:
          try {
            // 获取刷新令牌
            const refreshToken = await AsyncStorage.getItem('refreshToken');
            console.log('当前的refreshToken:', refreshToken);

            if (!refreshToken) {
              throw new Error('No refresh token available');
            }

            // 请求新的访问令牌
            console.log('开始请求刷新token...');
            const response = await instance.post("/refreshToken", {
              maxtoken: refreshToken
            });
            console.log(response,"这是返回");

            console.log('刷新token响应:', response.data);

            // 检查响应中是否包含新的访问令牌
            if (!response.setAccessToken) {
              console.log('刷新token响应格式错误:', response.data);
              throw new Error('Invalid refresh token response');
            }

            const newAccessToken = response.setAccessToken;
            console.log('获取到新的accessToken:', newAccessToken);

            // 更新访问令牌
            await AsyncStorage.setItem('accessToken', newAccessToken);

            // 更新请求头
            instance.defaults.headers['Authorization'] = newAccessToken;
            originalRequest.headers['Authorization'] = newAccessToken;

            console.log('准备重试原始请求:', originalRequest.url);
            // 重试原始请求
            const retryResponse = await instance(originalRequest);
            console.log('重试请求成功:', retryResponse);
            return retryResponse;
          } catch (refreshError) {
            console.error('刷新token失败:', refreshError);
            // 刷新令牌失败，清除所有令牌并跳转到登录页
            await AsyncStorage.removeItem('accessToken');
            await AsyncStorage.removeItem('refreshToken');
            await AsyncStorage.removeItem('userInfo');

            navigationRef.current?.dispatch(
              CommonActions.reset({
                index: 0,
                routes: [{ name: 'Login' }],
              })
            );
            return Promise.reject(new Error('登录已过期，请重新登录'));
          }
        default:
          return Promise.reject(new Error(error.response.data.message || '服务器错误'));
      }
    }

    return Promise.reject(new Error('网络连接失败，请检查网络设置'));
  }
);

export default instance;